/*
 * @Author: “ygnnli” “1585923072@qq.com”
 * @Date: 2024-08-01 18:50:39
 * @LastEditors: “ygnnli” “1585923072@qq.com”
 * @LastEditTime: 2024-08-01 19:24:02
 * @FilePath: /110/40/testCond.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <vector>
#include <pthread.h>
#include <string.h>
#include <unistd.h>

pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;    // 条件变量
pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER; // 互斥锁

void *MasterCore(void *args)
{
    sleep(3);
    std::cout << "master 开始工作..." << std::endl;
    std::string name = static_cast<const char *>(args);
    while (1)
    {
        // pthread_cond_signal(&gcond);
        pthread_cond_broadcast(&gcond); // 唤醒所有
        std::cout << "master 唤醒的线程是：" << std::endl;
        sleep(1);
    }
}

void StartMaster(std::vector<pthread_t> *tidsptr)
{
    pthread_t tid;
    int n = pthread_create(&tid, nullptr, MasterCore, (void *)"Master Thread");
    if (n == 0)
    {
        std::cout << "create Master success" << std::endl;
        tidsptr->emplace_back(tid);
    }
}
void *SlaverCore(void *args)
{
    std::string name = static_cast<const char *>(args);
    while (1)
    {
        // 加锁
        pthread_mutex_lock(&gmutex);

        pthread_cond_wait(&gcond, &gmutex);
        std::cout << "当前被叫醒的线程是: " << name << std::endl;

        // 解锁
        pthread_mutex_unlock(&gmutex);
    }
}

void StartSlaver(std::vector<pthread_t> *tidsptr, int threadnum = 3)
{
    for (int i = 0; i < threadnum; ++i)
    {
        char *name = new char[64];
        snprintf(name, 64, "Slaver Thread- %d", i + 1);
        pthread_t tid;
        int n = pthread_create(&tid, nullptr, SlaverCore, name);
        if (n == 0)
        {
            std::cout << "create Master success" << std::endl;
            tidsptr->emplace_back(tid);
        }
    }
}

void WaitThread(std::vector<pthread_t> *tids)
{
    for (auto &tid : *tids)
    {
        pthread_join(tid, nullptr);
    }
}

int main()
{
    std::vector<pthread_t> tids;

    StartMaster(&tids); // 启动一批线程
    StartSlaver(&tids);

    WaitThread(&tids);

    return 0;
}